<?php
/**
 * Created by PhpStorm.
 * User: edmmss
 * Date: 2018/12/12
 * Time: 22:47
 */

namespace app\modules\iterator;


class BookList implements \Countable, \Iterator
{
    /**
     * @var array
     */
    private $_books = [];

    /**
     * @var int
     */
    private $currentIndex = 0;

    public function addBook(Book $book)
    {
        $this->_books[] = $book;
    }

    public function removeBook(Book $bookToRemove)
    {
        foreach ($this->_books as $key => $book) {
            /* @var $book Book */
            if ($book->getAuthorAndTitle() === $bookToRemove->getAuthorAndTitle()) {
                unset($this->_books[$key]);
            }

            $this->_books = array_values($this->_books);
        }
    }

    /**
     * className
     *
     * @date   2018/12/12
     * @author edmmss
     * @return int
     */
    public function count(): int
    {
        // TODO: Implement count() method.
        return count($this->_books);
    }

    /**
     * className
     *
     * @date   2018/12/12
     * @author edmmss
     * @return mixed
     */
    public function current(): Book
    {
        // TODO: Implement current() method.
        echo __METHOD__ . '<br>';

        return $this->_books[$this->currentIndex];
    }

    /**
     * className
     *
     * @date   2018/12/12
     * @author edmmss
     */
    public function next()
    {
        // TODO: Implement next() method.
        echo __METHOD__ . '<br>';

        $this->currentIndex++;
    }

    /**
     * className
     *
     * @date   2018/12/12
     * @author edmmss
     * @return mixed
     */
    public function key(): int
    {
        // TODO: Implement key() method.
        echo __METHOD__ . '<br>';

        return $this->currentIndex;
    }

    /**
     * className
     *
     * @date   2018/12/12
     * @author edmmss
     * @return bool
     */
    public function valid(): bool
    {
        // TODO: Implement valid() method.
        echo __METHOD__ . '<br>';

        return isset($this->_books[$this->currentIndex]);
    }

    /**
     * className
     *
     * @date   2018/12/12
     * @author edmmss
     */
    public function rewind()
    {
        // TODO: Implement rewind() method.
        echo __METHOD__ . '<br>';

        $this->currentIndex = 0;
    }
}